package com.situ.springbootscientific.controller;


import com.situ.springbootscientific.constant.ImageConstants;
import com.situ.springbootscientific.utils.AliOSSUtils;
import com.situ.springbootscientific.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
public class UploadController {
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping("/upload")
    public Result uploadImage(MultipartFile file) {
        // 文件校验
        if (file == null || file.isEmpty()) {
            return Result.error("文件不能为空");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.matches("^.*\\.(jpg|jpeg|png|gif|bmp)$")) {
            return Result.error("请上传图片文件（jpg、jpeg、png、gif、bmp）");
        }

        // 生成唯一的文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = uuid + suffix;

        System.out.println("UUID图片名：" + newFileName);

        // 上传文件到OSS
        String url;
        try (InputStream inputStream = file.getInputStream()) {
            // 上传文件到阿里云OSS
            url = AliOSSUtils.uploadFile(newFileName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败：" + e.getMessage());
        }

        // 将图片URL存入Redis
        redisTemplate.opsForSet().add(ImageConstants.UPLOAD_IMAGE, url);

        redisTemplate.opsForSet().add(ImageConstants.UPLOAD_IMAGE_TO_DB,url);

        return Result.ok("上传成功", url);
    }
}
